﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Device.Location;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Notification;
using System.IO;
using System.Diagnostics;
using System.ComponentModel;

using Microsoft.Advertising.Mobile.UI;
using WindowsPhoneRecipes;
using ActivityTracker.Library;

using Microsoft.Phone.Net.NetworkInformation;

using System.Windows.Threading;
using Common.Library;
using OnlineVideos.Services.FileStoreService;

namespace ActivityTracker
{
    public partial class App : Application
    {
        public static string actId = null;
        public static string actName = null;
        public static string runningActId = null;
       
        public static DateTime actStartDate = System.DateTime.Now;
        public static DateTime lapStartTime = System.DateTime.Now;
        public static string schedId = null;
        public static string schedName = null;
        public static DateTime schedStartDate = System.DateTime.Now;
        public static DateTime schedStartTime = System.DateTime.Now;
        public static DateTime schedEndDate = System.DateTime.Now;
        public static DateTime schedEndTime = System.DateTime.Now;
        public static int lapCount = 0;
        public static bool LocTrackingStatus = false;
        public static ImageSource AcitivityImgSrc;
        public static ImageSource AcitivityImgSrc1;
        public static byte[] ImageBytes = null;
        public static int lstPkrActivityid = 0;
        private DispatcherTimer timer;
      
    
        /// <summary>
        /// Provides easy access to the root frame of the Phone Application.
        /// </summary>
        /// <returns>The root frame of the Phone Application.</returns>
        public PhoneApplicationFrame RootFrame { get; private set; }
        IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
     
        /// <summary>
        /// Constructor for the Application object.
        /// </summary>
        public App()
        {
            // Global handler for uncaught exceptions. 
            UnhandledException += Application_UnhandledException;

            // Show graphics profiling information while debugging.
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // Display the current frame rate counters.
                Application.Current.Host.Settings.EnableFrameRateCounter = true;

                // Show the areas of the app that are being redrawn in each frame.
                //Application.Current.Host.Settings.EnableRedrawRegions = true;

                // Enable non-production analysis visualization mode, 
                // which shows areas of a page that are being GPU accelerated with a colored overlay.
                //Application.Current.Host.Settings.EnableCacheVisualization = true;
            }

            // Standard Silverlight initialization
            InitializeComponent();
           

            //AdControl.TestMode = false;
            //if (ExtendedPropertyHelper.GetWindowsLiveAnonymousID() != "")
            //    AdControl.WindowsLiveANID = ExtendedPropertyHelper.GetWindowsLiveAnonymousID();
          //  LoadDictionary();
            // Phone-specific initialization
            InitializePhoneApplication();
        }
        private void LoadDictionary()
        {


            var dictionaries = Resources.MergedDictionaries;
            dictionaries.Clear();

            var themeStyles = new ResourceDictionary { Source = new Uri("/ActivityTracker;component/onlinemoviesstyle.xaml", UriKind.Relative) };
            dictionaries.Add(themeStyles);
        }
        // Code to execute when the application is launching (eg, from Start)
        // This code will not execute when the application is reactivated
        private void Application_Launching(object sender, LaunchingEventArgs e)
        {
            try
            {
                Actvity objActivity = new Actvity();
                objActivity.CreateFileDirectory();
                objActivity.SaveDefaultActivities();
                Category objCategory = new Category();
                objCategory.SaveDefaultCategories();
                History objHistory = new History();
                objHistory.SaveDefaultTotalDurations();
                objHistory.SaveDefaultCategoryTotalDurations();
                Data objHelpData = new Data();
                objHelpData.CreateFileDirectory();
                objHelpData.SaveDefaultActivities();
                timer = new DispatcherTimer();
                timer.Interval = TimeSpan.FromSeconds(5);
                timer.Tick += new EventHandler(timer_Tick);
                //if (ExtendedPropertyHelper.GetWindowsLiveAnonymousID() != "")
                //    AdControl.WindowsLiveANID = ExtendedPropertyHelper.GetWindowsLiveAnonymousID();
                //SettingsHelper.save("TipsAndTricks", "true");
                bool AppLevelState = true;
                if (settings.Contains("AppLevelState"))
                    AppLevelState = Convert.ToBoolean(settings["AppLevelState"]);
                SettingsHelper.Save("AboutUsUpgrade","false");
                SettingsHelper.Save("Msuid", "28360");
                SettingsHelper.Save("CheckMicrosoftAds", "c8736437-6eec-403e-b9d4-333c4e6794d1");
                SettingsHelper.Save("AdVisible", "true");
                if (AppLevelState == true)
                {
                    MessageBoxResult resultLocService = MessageBox.Show("In order to deliver location tracking services, Activity Tracker needs permission to use the geo location services on the device. Without this permission location tracking would not be active when an activity is running. \n\n\n Do you want to allow Activity Tracker to use location service?", "Location Service", MessageBoxButton.OKCancel);
                    if (resultLocService == MessageBoxResult.OK)
                    {
                        SettingsHelper.Save("GeoLocationStatus", "true");
                        MessageBoxResult resultRunUnderLock = MessageBox.Show("In order to deliver tracking services Activity Tracker needs permission to run under the phone's locked screen. Without this permission tracking services will be suspended whenever display gets locked. \n\n\n Do you want to allow Activity Tracker to run during screen locks?", "Run Under Lock Screen", MessageBoxButton.OKCancel);
                        if (resultRunUnderLock == MessageBoxResult.OK)
                        {
                         ApplicationIdleModeHelper.Current.HasUserAgreedToRunUnderLock = true;
                            SettingsHelper.Save("runUnderLock", "true");
                        }
                        else
                            SettingsHelper.Save("runUnderLock", "false");
                    }
                    else
                        SettingsHelper.Save("GeoLocationStatus", "false");

                    SettingsHelper.Save("AppLevelState", "false");
                }

                if (!settings.Contains("TipsAndTricks"))
                {
                    //for the first time tips & tricks are enabled.
                    SettingsHelper.Save("TipsAndTricks", "true");
                }

               
               
            }
            catch (Exception ex)
            {
                string mess = "Exception in Application_Launching Method In App.Xaml file.\n\n" + ex.Message + "\n\n Stack Trace:- " + ex.StackTrace;
                Exceptions.SaveOrSendExceptions(mess, ex);
            }
        }
        void timer_Tick(object sender, EventArgs e)
        {
            try
            {
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    if (NetworkInterface.NetworkInterfaceType != NetworkInterfaceType.None)
                    {
                        DeviceHelper.GetDeviceUniqueID();
                        Service1Client client = new Service1Client();
                        client.GetAppCountCompleted += new EventHandler<GetAppCountCompletedEventArgs>(client_GetAppCountCompleted);
                        client.GetAppCountAsync(DeviceHelper.GetDeviceUniqueID(), "0", DateTime.Now);
                    }
                }
            }
            catch (Exception ex)
            {
                Exception exnew = new Exception("Exception in timer_Tick Method In StartActivity file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                throw exnew;
            }
        }
        // Code to execute when the application is activated (brought to foreground)
        // This code will not execute when the application is first launched
        private void Application_Activated(object sender, ActivatedEventArgs e)
        {
        }

        // Code to execute when the application is deactivated (sent to background)
        // This code will not execute when the application is closing
        private void Application_Deactivated(object sender, DeactivatedEventArgs e)
        {
        }

        // Code to execute when the application is closing (eg, user hit Back)
        // This code will not execute when the application is deactivated
        private void Application_Closing(object sender, ClosingEventArgs e)
        {
        }

        // Code to execute if a navigation fails
        private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // A navigation has failed; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        // Code to execute on Unhandled Exceptions
        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            

            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }

        }

        #region Phone application initialization

        // Avoid double-initialization
        private bool phoneApplicationInitialized = false;
      

        // Do not add any additional code to this method
        private void InitializePhoneApplication()
        {
            if (phoneApplicationInitialized)
                return;

            // Create the frame but don't set it as RootVisual yet; this allows the splash
            // screen to remain active until the application is ready to render.
            RootFrame = new PhoneApplicationFrame();
            //RootFrame = new TransitionFrame();
            RootFrame.Navigated += CompleteInitializePhoneApplication;

            // Handle navigation failures
            RootFrame.NavigationFailed += RootFrame_NavigationFailed;

            // Ensure we don't initialize again
            phoneApplicationInitialized = true;

            NonLinearNavigationService.Instance.Initialize(RootFrame);
        }

        // Do not add any additional code to this method
        private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
        {
            // Set the root visual to allow the application to render
            if (RootVisual != RootFrame)
                RootVisual = RootFrame;

            // Remove this handler since it is no longer needed
            RootFrame.Navigated -= CompleteInitializePhoneApplication;
          ApplicationIdleModeHelper.Current.Initialize();
        }

        #endregion

        static void client_GetAppCountCompleted(object sender, GetAppCountCompletedEventArgs e)
        {
            if (e.Result != null)
            {
                SettingsHelper.Save("RelatedAppCount", e.Result);
            }
        }
    }
}